<template>
  <div id="app">
    <div class="return"  @click="back">
      <img class="backImg" src="@/assets/images/back.png" alt />
    </div>
    <div class="form">
      <!-- <h2 >{{cdInfo.customer_name}}病例</h2> -->
      <div class="title">客户基本信息</div>
      <el-form :model="cdInfo" label-width="100px">
        <el-row :gutter="150">
          <el-col :span="12">
            <el-form-item label="患者姓名：">
              <el-input v-model="cdInfo.customer_name" readonly size="mini"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="主诊医生：">
              <el-input v-model="cdInfo.doctor_name" readonly size="mini"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="150">
          <el-col :span="12">
            <el-form-item label="患者性别：">
               <el-radio-group v-model="cdInfo.customer_sex_text">
                  <el-radio  label="男">男性</el-radio>
                  <el-radio  label="女">女性</el-radio>
                </el-radio-group>
            </el-form-item>                                
          </el-col>
          <el-col :span="12">                        
            <el-form-item label="病例单号：">
              <el-input v-model="cdInfo.case_no"  readonly size="mini"></el-input>
            </el-form-item>
          </el-col>         
        </el-row>

        <el-row :gutter="150">
          <el-col :span="12">
            <el-form-item label="患者生日：">
              <el-input v-model="cdInfo.customer_birth_date" readonly size="mini"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="就诊日期：">
              <el-input v-model="cdInfo.treatment_date" readonly size="mini"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
       <div class="title">详细病例信息</div>
      <el-form :model="caseInfo" :rule="rules" ref="caseInfo" label-width="100px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="病例状态：" prop="case_type">
                <el-radio-group v-model="caseInfo.case_type" :disabled="readonly">
                  <el-radio  :label="1">初诊</el-radio>
                  <el-radio  :label="2">复诊</el-radio>
                </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="患者主诉：" prop="principle_action">
              <el-input v-model="caseInfo.principle_action"  type="textarea"  :readonly="readonly" size="mini" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
            <el-col :span="8">
              <el-form-item label="既往过敏史："  >
                <el-radio-group v-model="caseInfo.is_previous_history" :disabled="readonly">
                  <el-radio  :label="0">无</el-radio>
                  <el-radio  :label="1">有</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="16">
              <el-form-item  prop="previous_allergy_history"  v-if="caseInfo.is_previous_history == 1" label-width="0">
                  <el-input v-model="caseInfo.previous_allergy_history"   :readonly="readonly" size="mini" placeholder="请输入内容"></el-input>
              </el-form-item>
            </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="既往史：" prop="previous_history" >
              <el-input v-model="caseInfo.previous_history" :readonly="readonly" size="mini" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="家族史：" prop="is_family_history">
              <el-radio-group v-model="caseInfo.is_family_history" :disabled="readonly">
                  <el-radio  :label="0">无</el-radio>
                  <el-radio  :label="1">有</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item  prop="is_family_history" v-if="caseInfo.is_family_history == 1" label-width="0">
                <el-input   v-model="caseInfo.family_history"  :readonly="readonly" size="mini" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-col>

        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="皮肤检查：" prop="">
              <el-input v-model="caseInfo.skin_examine" type="textarea" :rows="2" :readonly="readonly" size="mini" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row >
          <el-col :span="24">
            <el-form-item label="辅助检查：" prop="auxiliary_examine">
              <el-input v-model="caseInfo.auxiliary_examine"  type="textarea" :rows="2" :readonly="readonly" size="mini" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row style="display: flex;align-items: center;" :gutter="50" v-for="(item,index) in diag" :key="index">
          <el-col :span="22">
            <el-row>  
                <el-col :span="24">
                  <el-form-item label="诊断：" prop="type">
                    <el-cascader
                      v-model="item.type"
                      :options="options.typeList"
                      :disabled="readonly"
                      class="w300"
                      @change="changeSourceType(item,index)"
                      size="mini"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24">
                  <el-form-item label="医嘱：" prop="advice_doctor">
                    <el-input v-model="item.advice_doctor" type="textarea" :rows="2" :readonly="readonly" size="mini" placeholder="请输入内容"> </el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24">
                  <el-form-item label="治疗方案：" prop="therapeutic_schedule">
                    <el-input v-model="item.therapeutic_schedule"  type="textarea" :rows="2" :readonly="readonly" size="mini" placeholder="请输入内容"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
          </el-col>
          <el-col :span="2">
           <i class="el-icon-plus" style="color: #33bea7;cursor: pointer;" @click="addType"  v-if="index == (diag.length-1) && diag.length !== 3 && !readonly"></i>
           <i class="el-icon-minus" style="color: #33bea7;cursor: pointer;" @click="reduceType(index)" v-if="index !== (diag.length-1) && !readonly"></i>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <div style="float: right;display: flex;align-items: center;">
              <span>医生签名：</span>
              <img :src="'data:image/png;base64,'+ e_signature_doctor" alt="签名图片">
            </div>  
          </el-col>
        </el-row>
      </el-form>
      <div class="btnBox" v-if="!readonly">
      <el-button
        type="primary"
        size="mini"
        class="mainBtn"
        @click="submitForm('caseInfo')"
      >{{kind == 'edit' ? '编辑':'新增'}}提交</el-button>
    </div>
    </div>
 
  </div>
</template>

<script>
import{addCustomerCase,updateCustomerCase,getCustomerCaseDetail}from '@/api/client';
import { goodsTypeList } from '@/api/goods';
import { mapGetters } from "vuex";
import { convertToTreeData } from '@/utils/constants';
class CaseInfo  {
  case_type =	'';
  diagnose_category_two='';
  diagnose_category_three='';
  principle_action='';
  previous_allergy_history=	'';
  now_medical_history=	'';
  previous_history='';
  family_history='';
  skin_examine='';
  auxiliary_examine='';
  diag=[];
  // diagnose_category_one=	'';
  // diagnose_category_two='';
  // diagnose_category_three='';
  // advice_doctor='';
  // therapeutic_schedule='';	
  is_previous_history=0;
  is_family_history=0;
}
class Diag {
  type ='';
  diagnose_category_one=	'';
  diagnose_category_two='';
  diagnose_category_three='';
  advice_doctor='';
  therapeutic_schedule='';	
}
class Rules {
  // name = [
  //   { required: true, message: '请填写品项名称', trigger: 'blur' }
  // ];
  // type = [
  //   { required: true, message: '请选择品项类型', trigger: 'blur' }
  // ];
  // number = [
  //   { required: true, message: '请填写次数', trigger: 'change' }
  // ];
  // price = [
  //   { required: true, message: '请填写组合价格', trigger: 'blur' }
  // ];
}
class Options {
  typeList = [];
  caseTypeList = [
    { label: '复诊病例', value: 2 },
    { label: '初诊病例', value: 1 } 
  ];
}

export default {
  data() {
    return {
      radio:1,
      kind:this.$route.query.kind,
      options: new Options(),
      cdInfo: JSON.parse(sessionStorage.getItem('cdInfo')) || {},
      readonly: false,
      caseInfo: new CaseInfo(),
      rules: new Rules(),
      threeList:[],
	    e_signature_doctor:'',
      diag:[new Diag()]
    }
  },
  computed: {
    ...mapGetters(["userInfo"])
  },
  mounted () {
    this.getOptionsList();
    console.log(this.$route.query);
    if(this.$route.query.kind == 'read') this.readonly = true, this.getCaseInfo(this.$route.query.caseId);
    if(this.$route.query.kind == 'edit') this.getCaseInfo(this.$route.query.caseId);

  },
  beforeRouteEnter(to, from, next) {
    if (from.name !== null) {
      next(vm => {
        vm.addCase();
      });
    } else {
      next();
    }
  },
  beforeDestroy(){
    sessionStorage.removeItem('cdInfo');
  },
  methods: {
    // 病例详情
    // /order/caseOrderDetail


    // 新增病例
    addCase() {
      if(this.$route.query.caseId) return;
      addCustomerCase({customer_id:this.$route.query.detail.id,doctor_id:this.userInfo.shop_person_id}).then(res => {
        this.cdInfo = res.data;
		    this.e_signature_doctor = res.data.sign_img;
        sessionStorage.setItem('cdInfo',JSON.stringify(res.data));
      })
    },
    // 获取病例详情
    getCaseInfo(id){
      getCustomerCaseDetail({id:id}).then(res => {
        this.caseInfo = res.data;
        const  {customer_name,case_no,customer_sex,customer_birth_date,doctor_name,treatment_date,id,e_signature_doctor} = res.data;
        this.cdInfo = {customer_name,case_no,customer_birth_date,doctor_name,treatment_date,id};
		    this.e_signature_doctor = e_signature_doctor
        this.cdInfo.customer_sex_text = customer_sex == 2 ?'女' :'男';
        this.diag = res.data.diags
        if(this.diag.length == 0) this.diag.push(new Diag());

      }) 
    },
    reduceType(index){
      this.diag.splice(index,1);
    },
    addType(){
      if(this.diag.length >2){
        this.$message.warning('只能新增三项')
      }else{
        this.diag.push(new Diag());
      }
    },
    changeSourceType(e,index){
      console.log(e,index)
      this.diag[index].diagnose_category_one = e.type[0];
      this.diag[index].diagnose_category_two = e.type[1];
      this.diag[index].diagnose_category_three = e.type[2];
       this.diag[index].advice_doctor =  this.threeList.find(item => item.id == e.type[2]).doctor_advice;
    },
    getOptionsList(){
      goodsTypeList({type:'all'}).then(res => {
        // 过滤没有子项的项
        this.options.typeList = res.data.filter(item => {
          if (!item.children || item.children.length === 0) {
            return false; // 没有子项则过滤
          }
          // 二级过滤
          item.children = item.children.filter(child => {
            if (!child.children || child.children.length === 0) {
              return false;
            }
            return true;
          });
          
          return item.children.length > 0; // 确保至少有一个子项
        });
        this.options.typeList = convertToTreeData(this.options.typeList);

          // 获取第三级数组
        this.threeList = res.data
          .filter(item => item.children) // 过滤掉没有children的项
          .flatMap(item => item.children)
          .filter(child => child.children) // 过滤掉没有children的子项
          .flatMap(child => child.children || []);
          })
    },
    
    back () {
       // 返回
      const query = {
        detail: this.$route.query.detail,
        id: this.$route.query.detail.id,
        activeName: "fourteen"
      };
      this.$router.push({ name: "客户详情", query });
    },
   
      // 提交
    submitForm (formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.hint(this.kind == 'edit'? '编辑':'新增');
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
     hint(text){
       this.$confirm(`确定${text}此病例吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.saveCase()
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          });
        });
    },
    saveCase () {
      this.caseInfo.diag = this.diag
	  this.caseInfo.e_signature_doctor= this.e_signature_doctor;
      console.log(this.caseInfo,"this.caseInfo")
      updateCustomerCase({
        ...this.caseInfo,
        customer_id: this.$route.query.detail.id,
        doctor_id: this.userInfo.shop_person_id,
        id:	 this.cdInfo.id
      }).then(res => {
        this.$message({
          message: '保存成功',
          type: 'success'
        });
        this.back();
      })
     
    }
  }
}
</script>

<style lang="scss" scoped>

.return {
  position: fixed;
  right: 20px;
  top: 71px;
  z-index: 999;
  .backImg {
    margin-right: 14px;
    width: 32px;
    height: 100%;
    cursor: pointer;
    vertical-align: middle;
  }
}
.btnBox{
  margin-top:40px;
  text-align: center;
}
.form {
  width:60%;
  .title {
    font-weight: bold;
    font-size: 14px;
    padding: 10px 20px;
    color: #666;
    background: #F5F7FA;
    margin-bottom: 10px;
  }

  ::v-deep .region .el-select {
    width: 100px;
  }
  ::v-deep .el-form{
    width: 95%;
    margin: 0 auto;
  }
  ::v-deep .el-col{
    margin: 3px 0;
  }
  ::v-deep .el-cascader--mini{
    width: 100% !important;
  }

}

.el-form-item {
  margin-bottom: 10px;
}
::v-deep .el-input.is-disabled .el-input__inner{
  background-color: #ffffff;
  color: #606266;
}
</style>